package com.javatom.notes.mongo.service;

import com.javatom.notes.mongo.mapper.TestDataInfoMapper;
import com.javatom.notes.mongo.po.ProcessPo;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class MongoOperatService {
    @Resource
    private TestDataInfoMapper testDataInfoMapper;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 初始化表数据
     * @param applicationName
     * @return
     */
    public boolean initData(String applicationName) {
        log.error("applicationName {}",applicationName);
        List<ProcessPo>  processPos= testDataInfoMapper.findTop200();
        log.error("ProcessPo {}",processPos.get(0));
        Collection<ProcessPo> insert = mongoTemplate.insert(processPos, ProcessPo.class);
        log.error("insert.isEmpty() {}",insert.isEmpty());
        return insert.isEmpty();
    }

    /**
     * 删除集合
     * @return
     */
    public boolean delAll() {
        mongoTemplate.dropCollection(ProcessPo.class);
        return true;
    }
    /**
     * 根据id 查询
     */
    public ProcessPo  findById(String id){
        ProcessPo byId = mongoTemplate.findById(id, ProcessPo.class);
        log.error("结果体 {}",byId);
        return byId;
    }
    /**
     * 简单条件查询，查询出有list
     * select * from es_info where table_name='' and project_id=''  and  audit_status=1 or audit_status=2
     */
    public List<ProcessPo>   findByCondition(String table_name,
                                             String project_id,
                                             String audit_status){
        /**
         * where(key) 添加条件 key==字段值
         */
        Query query=new Query();
        Criteria criteria=Criteria.where("table_name").is(table_name).and("project_id").is(project_id)
                .and("audit_status").is(audit_status);
        query.addCriteria(criteria);
        List<ProcessPo> processPos = mongoTemplate.find(query, ProcessPo.class);
        log.error("使用mongoTemplate 结果体 {}",processPos);
        ProcessPo one = mongoTemplate.findOne(query, ProcessPo.class);
        log.error("使用mongoTemplate findOne 结果体 {}",one);

        return processPos;
    }

//    /**
//     * 过滤查询
//     * @return
//     */
//    public List<ProcessPo>   findByCondition2(){
//
//        return ;
//    }

    /**
     * 范围查询
     */
    public List<ProcessPo>   findByCondition1(){
        Query query=new Query();
        // lt 小于
        //gt 大于
        //$gt	>
        //$gte	>=
        //$eq	=
        //$ne	!=
        //$lt	<
        //$lte	<=
        //$in	in(后面的值为bson对象数组)
        //$nin	not in(后面的值为bson对象数组)
        Criteria criteria=Criteria.where("audit_status").is(1)
                .and("create_time").gt(dateToISODate("2019-03-13 16:00:00"));
        query.addCriteria(criteria);
        List<ProcessPo> processPos = mongoTemplate.find(query, ProcessPo.class);
        log.error("processPos {} ",processPos.size());
        Criteria criteria1=Criteria.where("audit_status").is(2)
                .andOperator(
                        Criteria.where("create_time").lt(dateToISODate("2019-06-13 16:00:00")),
                        Criteria.where("create_time").gt(dateToISODate("2019-03-13 16:00:00"))

                );

        query.addCriteria(criteria1);
        List<ProcessPo> processPos1 = mongoTemplate.find(query, ProcessPo.class);
        log.error("processPos {} ",processPos1.size());
        return null;

    }


    /**
     * 简单增加，简单修改，简单删除
     */
    public void insertAndUpdateAndDel(){
        ProcessPo processPo=new ProcessPo();
        processPo.setId("123456789");
        processPo.setBusinessId("1249895787719204865");
        processPo.setTableName("曾维录Test");
        processPo.setProjectName("曾维录操作Modb测试");
          mongoTemplate.insert(processPo);
        log.info("增加: {} " , processPo);
        ProcessPo byId = mongoTemplate.findById("123456789", ProcessPo.class);
        log.error("查出来的数据 {}",byId);
        UpdateResult updateResult = mongoTemplate.updateFirst(new Query(
                        Criteria.where("id").is("123456789").and("business_id").is("21")),
                new Update().set("table_name", "这是修改后的结果"), ProcessPo.class);
        ProcessPo byId1 = mongoTemplate.findById("123456789", ProcessPo.class);
        log.error("第一次修改会失败 updateResult {}", updateResult);
        log.error("第一次修改会失败 {}",byId1);

        UpdateResult updateResult1 = mongoTemplate.updateFirst(new Query(
                        Criteria.where("id").is("123456789").and("business_id").is("1249895787719204865")),
                new Update().set("table_name", "这是修改后的结果"), ProcessPo.class);
        ProcessPo byId2 = mongoTemplate.findById("123456789", ProcessPo.class);
        log.error("第二次修改会成功 updateResult {}", updateResult1);
        log.error("第二次修改会成功 {}",byId2);

        DeleteResult id = mongoTemplate.remove(new Query(Criteria.where("id").is("123456789")), ProcessPo.class);
        log.error("删除 {}",id);
    }
    /**
     * mongo 日期查询isodate
     * @param dateStr
     * @return
     */
    public static Date dateToISODate(String dateStr){
        //T代表后面跟着时间，Z代表UTC统一时间
        Date date = formatD(dateStr);
        return date;
//        SimpleDateFormat format =
//                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
//        format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
//        String isoDate = format.format(date);
//        try {
//            return format.parse(isoDate);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        return null;
    }
    /** 时间格式(yyyy-MM-dd HH:mm:ss) */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static Date formatD(String dateStr){
        return formatD(dateStr,DATE_TIME_PATTERN);
    }

    public static Date formatD(String dateStr ,String format)  {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date ret = null ;
        try {
            ret = simpleDateFormat.parse(dateStr) ;
        } catch (ParseException e) {
            //
        }
        return ret;
    }


}
